package com.cn.intelligence.resetful.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cn.intelligence.mapper.TbAddressMapper;
import com.cn.intelligence.mapper.TbCartMapper;
import com.cn.intelligence.mapper.TbItemMapper;
import com.cn.intelligence.mapper.TbOrderMapper;
import com.cn.intelligence.mapper.TbUserMapper;
import com.cn.intelligence.mapper.VipMapper;
import com.cn.intelligence.pojo.TaotaoResult;
import com.cn.intelligence.pojo.TbAddress;
import com.cn.intelligence.pojo.TbAddressExample;
import com.cn.intelligence.pojo.TbCart;
import com.cn.intelligence.pojo.TbCartExample;
import com.cn.intelligence.pojo.TbItem;
import com.cn.intelligence.pojo.TbItemExample;
import com.cn.intelligence.pojo.TbOrder;
import com.cn.intelligence.pojo.TbUser;
import com.cn.intelligence.pojo.TbUserExample;
import com.cn.intelligence.pojo.Vip;
import com.cn.intelligence.pojo.VipExample;
import com.cn.intelligence.resetful.pojo.EUICartInfo;
import com.cn.intelligence.resetful.pojo.OrderInfo;
import com.cn.intelligence.resetful.service.ShoppingService;
import com.cn.intelligence.util.IDUtils;

/**
 * 购物车信息
 * 
 * @author Administrator
 *
 */
@Service
public class ShoppingServiceImpl implements ShoppingService {

	/**
	 * 向购物车添加商品
	 */
	@Autowired
	TbCartMapper cartMapper;
	@Autowired
	TbUserMapper userMapper;
	@Autowired
	private TbItemMapper itemMapper;
	@Autowired
	public TbAddressMapper tbAddressMapper;
	@Autowired
	public TbOrderMapper tbOrderMapper;
	@Autowired
	public VipMapper vipMapper;
	@Autowired
	public TbUserMapper tbUserMapper;

	@Override
	public TaotaoResult saveCart(TbCart tbCart) throws Exception {
		Map<String, Long> map = new HashMap<String, Long>();
		// 查询改用户的购物车中有没有该商品
		TbCartExample ex = new TbCartExample();
		TbCartExample.Criteria crcat = ex.createCriteria();
		crcat.andUidEqualTo(tbCart.getUid());
		crcat.andPidEqualTo(tbCart.getPid());
		crcat.andStatusEqualTo("1");
		if(tbCart.getParams()!=null && !"".equals(tbCart.getParams())){
			crcat.andParamsEqualTo(tbCart.getParams());
		}
		
		List<TbCart> listcart = cartMapper.selectByExample(ex);
		if (listcart != null && listcart.size() > 0) {
			String num = listcart.get(0).getNum();
			Long newnum = Long.parseLong(tbCart.getNum()) + Long.parseLong(num);
			tbCart.setNum(Long.toString(newnum));
			tbCart.setUpdated(new Date());
//			cartMapper.updateByExampleSelective(tbCart, ex);
			map.put("cart_id", listcart.get(0).getId());
		} else {
			long id = IDUtils.genItemId();
			tbCart.setId(id);
			tbCart.setStatus("1");
			tbCart.setCreated(new Date());
			tbCart.setUpdated(new Date());
			// 插入商品
			int resut = cartMapper.insert(tbCart);

			
			if (resut <= 0) {
				throw new Exception();
			}
			map.put("cart_id", id);
		}
		
		TbItem item2 = new TbItem();
		item2 = itemMapper.selectByPrimaryKey(tbCart.getPid());
		
		TbItemExample tbItemexample = new TbItemExample();
		TbItemExample.Criteria criteria = tbItemexample.createCriteria();
		criteria.andIdEqualTo(tbCart.getPid());
		TbItem item = new TbItem();
		item.setShiyong(item2.getShiyong()+1);
		item.setUpdated(new Date());
		itemMapper.updateByExampleSelective(item, tbItemexample);
		TaotaoResult taotaoresult = new TaotaoResult(map);
		return taotaoresult;

	}

	/**
	 * 查询购物车信息
	 */
	@Override
	public Map<String, Object> getCartlist(Long userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<EUICartInfo> carinfoList = new ArrayList<EUICartInfo>();
		// 查询购物车信息
		TbCartExample example = new TbCartExample();
		TbCartExample.Criteria criteria = example.createCriteria();
		criteria.andUidEqualTo(userId);
		criteria.andStatusEqualTo("1");
		List<TbCart> cartlist = cartMapper.selectByExample(example);
		long total = 0;
		// 查询购物车商品详细信息
		for (TbCart tbCart : cartlist) {
			TbItemExample itemExample = new TbItemExample();
			TbItemExample.Criteria itemCriteria = itemExample.createCriteria();
			itemCriteria.andIdEqualTo(new Long(tbCart.getPid()));
			List<TbItem> itemlist = itemMapper.selectByExampleWithBLOBs(itemExample);
			if (itemlist.size() == 1) {
				EUICartInfo carinfo = new EUICartInfo();
				carinfo.setId(tbCart.getId());
				carinfo.setUserId(tbCart.getUid());
				carinfo.setTitle(itemlist.get(0).getName());
				carinfo.setNum(Integer.parseInt(tbCart.getNum()));
				carinfo.setPrice(Double.parseDouble(itemlist.get(0).getSprice().toString()));
				carinfo.setSumprice(new Double(Double.parseDouble(tbCart.getNum()) * Double.parseDouble(itemlist.get(0).getSprice())));
				carinfo.setPrid(tbCart.getPid());
				carinfo.setImage(itemlist.get(0).getPhotoX() != null ? itemlist.get(0).getPhotoX().split(",")[0] : "");
				carinfo.setSelected(true);
				carinfo.setParams(tbCart.getParams());
				carinfoList.add(carinfo);
				total += carinfo.getSumprice();
			}
		}

		map.put("cart", carinfoList);
		map.put("total", total);
		return map;
	}

	/**
	 * 删除购物车信息
	 */
	@Override
	public TaotaoResult deleteUserCart(Long cardId) {
		// 删除购物内容
		TbCartExample example = new TbCartExample();
		TbCartExample.Criteria criteria = example.createCriteria();
		criteria.andIdEqualTo(cardId);
		int resultvalue = cartMapper.deleteByExample(example);
		if (resultvalue > 0) {
			return TaotaoResult.ok();
		} else {
			return TaotaoResult.ok("删除失败");
		}

	}

	/**
	 * 获取购物车中的商品信息
	 * 
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> getBuyCat(String cart_id, Long uid) {
		String[] cartsid = cart_id.split(",");
		List<Long> cartsLongIds = new ArrayList<Long>();
		for (String crtsId : cartsid) {
			cartsLongIds.add(new Long(crtsId));
		}
		Map<String, Object> map = new HashMap<>();
		// 查询购物车信息
		TbCartExample example = new TbCartExample();
		TbCartExample.Criteria criteria = example.createCriteria();
		criteria.andUidEqualTo(uid);
		criteria.andIdIn(cartsLongIds);
		List<TbCart> cartlist = cartMapper.selectByExample(example);
		List<OrderInfo> orderInfoList = new ArrayList<OrderInfo>();
		Double hejijine = 0d;
		Double zhongliang = 0d;
		for (TbCart tbCart : cartlist) {
			OrderInfo orderInfo = new OrderInfo();
			// 查询商品信息
			TbItemExample itemExample = new TbItemExample();
			TbItemExample.Criteria itemCriteria = itemExample.createCriteria();
			itemCriteria.andIdEqualTo(new Long(tbCart.getPid()));
			List<TbItem> itemlist = itemMapper.selectByExampleWithBLOBs(itemExample);
			// 设定产品信息
			orderInfo.setPid(""+itemlist.get(0).getId());
			orderInfo.setPhotoX(itemlist.get(0).getPhotoX() == null ? "" : itemlist.get(0).getPhotoX().split(",")[0]);
			orderInfo.setName(itemlist.get(0).getName());
			orderInfo.setPrice(Double.parseDouble(itemlist.get(0).getSprice().toString()));
			orderInfo.setNum(Long.parseLong(tbCart.getNum()));
			orderInfo.setParams(tbCart.getParams());
			orderInfoList.add(orderInfo);
			hejijine += Double.parseDouble(itemlist.get(0).getSprice()) * Long.parseLong(tbCart.getNum());
			zhongliang += Long.parseLong(itemlist.get(0).getZhongliang()) * Long.parseLong(tbCart.getNum());

		}
		map.put("pro", orderInfoList);

		// 查询收货地址信息
		TbAddressExample addressexample = new TbAddressExample();
		TbAddressExample.Criteria criteriaAddress = addressexample.createCriteria();
		criteriaAddress.andUidEqualTo(uid);
		criteriaAddress.andIsDefaultEqualTo("1");
		List<TbAddress> list = tbAddressMapper.selectByExample(addressexample);
		// 查询该地址的邮费信息
		Double postfee = 0d;
		if (list == null || list.size() == 0) {
			map.put("addemt", 1);
		} else {
			postfee = getPostFee(list.get(0).getId(), zhongliang);
			map.put("adds", list.get(0));
			map.put("addemt", 0);
		}
		// 查询改用户名下，有效期内可以使用的券
		List<Map<String, Object>> listvou = new ArrayList<Map<String, Object>>();
		VipExample viexample = new VipExample();
		viexample.setOrderByClause("activeTimeStart asc");
		VipExample.Criteria vipcriteria = viexample.createCriteria();
		vipcriteria.andUidEqualTo(uid);
		vipcriteria.andActivetimestartLessThanOrEqualTo(new Date());
		vipcriteria.andActivetimeendGreaterThanOrEqualTo(new Date());
		List<Vip> viplist = vipMapper.selectByExample(viexample);
		List<Double>  sort = new ArrayList<Double>();
		for (Vip vip : viplist) {
			if(sort.contains(vip.getAmount())){
				continue;
			}
			sort.add(vip.getAmount());
			Map<String, Object> mapvou = new HashMap<>();
			mapvou.put("vid", vip.getId());
			mapvou.put("amount", vip.getAmount());
			mapvou.put("full_money", vip.getFullMoney());
			listvou.add(mapvou);
		}
		map.put("postfee", postfee);
		hejijine = hejijine + postfee;
		map.put("vou", listvou);

		// 合计金额
		map.put("total", hejijine);
		// 优惠金额
		map.put("vprice", hejijine);

		return map;
	}

	/**
	 * 创建订单
	 */
	@Override
	public TbOrder addpayment(TbOrder tborder) throws Exception {

		// 判断商品是几个商品，每一个商品创建一个订单
		List<Long> cartIdlist = new ArrayList<Long>();
		if (tborder.getCartId() != null && !"".equals(tborder.getCartId())) {
			String cartIds[] = tborder.getCartId().split(",");
			for (String cartId : cartIds) {
				cartIdlist.add(Long.parseLong(cartId));
			}

		}
		//int value = 0;
		//for (Long long1 : cartIdlist) {

			// 创建订单------------------------------------------
			// 创建订单ID
			Long orderId = IDUtils.genItemId();
			tborder.setOrderId(Long.toString(orderId));
			// 创建物流新---------------------------------
			// 查询商品
//			TbCart cart = cartMapper.selectByPrimaryKey(long1);
//			TbItem item = itemMapper.selectByPrimaryKey(cart.getPid());
//			// 1 邮费
//			tborder.setPostFee(getPostFee(tborder.getAddressId(),
//					Double.parseDouble(item.getZhongliang()) * Double.parseDouble(cart.getNum())));
			//tborder.setPostFee(tborder.getPostFee());
			// 5物流名称
			// tborder.setShippingName("中通");
			// 6物流单号
			// tborder.setShippingName("T" + orderId);
			// -------------------------------------------
			// 2交易状态
			tborder.setStatus(1);
			// 3订单创建时间
			tborder.setCreateTime(new Date());
			// 4订单更新时间
			//tborder.setCartId(Long.toString(long1));
			tborder.setUpdateTime(new Date());
			int value = tbOrderMapper.insert(tborder);
		//}
			//修改购物用户与推广者的关联关系
			
			TbUserExample userExample = new TbUserExample();
			TbUserExample.Criteria cartcriteria2 = userExample.createCriteria();

			cartcriteria2.andIdEqualTo(tborder.getUserId());
			if(userMapper.selectByPrimaryKey(tborder.getUserId()).getRelid() == 0 ){
				int userupvalue = userMapper.updateByKey(tborder.getMemberId(), userExample);
			}

		if (value != 1) {
			throw new Exception();
		}
		// 修改购物车状态-----------------------------------------------
		TbCartExample cartExample = new TbCartExample();
		TbCartExample.Criteria cartcriteria = cartExample.createCriteria();

		cartcriteria.andIdIn(cartIdlist);
		TbCart tbCart = new TbCart();
		tbCart.setUpdated(new Date());
		tbCart.setStatus("2");
		int upvalue = cartMapper.updateByExampleSelective(tbCart, cartExample);
		if (upvalue <= 0) {
			throw new Exception();
		}
		return tborder;
	}

	/**
	 * 计算运费 广东省内首重1kg以内4元 续重1元1kg 西北5省（甘肃，青海，内蒙古，新疆，宁夏）首重10元，续重5元，，西藏不发 其余省
	 * 首重都是6元，续重4元
	 * 
	 * @param addressId
	 * @return
	 */
	private Double getPostFee(Integer addressId, Double weight) {
		TbAddress address = tbAddressMapper.selectByPrimaryKey(addressId);
		String proviceId = address.getProvice();
		String weight_g = Double.toString(weight);
		// 商品重量
		BigDecimal weight_g_big = new BigDecimal(weight_g);
		// 合计费用
		BigDecimal totalFee = new BigDecimal(0);

		// 首重4元
		BigDecimal startFee = new BigDecimal(0);
		// 续重4元
		BigDecimal addFee = new BigDecimal(0);
		// 分割标准：多少公斤涨一次钱
		BigDecimal biaozhun = new BigDecimal(1000);
		// 广东省内首重1kg以内4元 续重1元1kg
		if ("440000".equals(proviceId)) {
			// 首重4元
			startFee = new BigDecimal(4);
			// 续重4元
			addFee = new BigDecimal(1);
			// 分割标准：多少公斤涨一次钱
			biaozhun = new BigDecimal(1000);
		} else if ("620000".equals(proviceId) || "630000".equals(proviceId) || "150000".equals(proviceId)
				|| "650000".equals(proviceId) || "640000".equals(proviceId)) {
			// 首重10元
			startFee = new BigDecimal(10);
			// 续重5元
			addFee = new BigDecimal(5);
			// 分割标准：多少公斤涨一次钱
			biaozhun = new BigDecimal(1000);
		} else {
			// 首重6元
			startFee = new BigDecimal(6);
			// 续重4元
			addFee = new BigDecimal(4);
			// 分割标准：多少公斤涨一次钱
			biaozhun = new BigDecimal(1000);
		}
		if (weight_g_big.subtract(biaozhun).doubleValue() < 0) {
			totalFee = startFee;
		} else {
			BigDecimal xufeifee = (weight_g_big.subtract(biaozhun).divide(biaozhun)).multiply(addFee).setScale(0,
					BigDecimal.ROUND_HALF_UP);
			totalFee = xufeifee.add(startFee);
		}
		return totalFee.doubleValue();
	}

	@Override
	public TbCart updateCart(TbCart tbCart) {
		TbCartExample example = new TbCartExample();
		TbCartExample.Criteria criteria = example.createCriteria();
		criteria.andUidEqualTo(tbCart.getUid());
		criteria.andIdEqualTo(tbCart.getId());
		tbCart.setUpdated(new Date());
		int value = cartMapper.updateByExampleSelective(tbCart, example);
		if (value > 0) {
			return tbCart;
		} else {
			return null;
		}

	}

	/**
	 * 生产用户的VIp优惠券信息
	 * 
	 * @param vip
	 * @return
	 */
	@Override
	public List<Vip> setVipInfo(Vip vip) {
		// 查询改用户名下，有效期内可以使用的券
		VipExample viexample = new VipExample();
		VipExample.Criteria vipcriteria = viexample.createCriteria();
		vipcriteria.andUidEqualTo(vip.getUid());
		 DateTime dateTime = new DateTime(new Date());  
		 String  dateTimeStr = dateTime.toString("yyyy-MM-dd");  
		 DateTime today = DateTime.parse(dateTimeStr);
		DateTime tomdate = today.plusDays(1);
		vipcriteria.andCreatedLessThan(tomdate.toDate());
		vipcriteria.andCreatedGreaterThan(today.toDate());
		List<Vip> viplist = vipMapper.selectByExample(viexample);
		// 每个人每天只能有两张优惠券
		if(viplist.size()<2){
		// 如果没有优惠券，则发放一个优惠券
			
			TbUser tbuser = tbUserMapper.selectByPrimaryKey(vip.getUid());
			long ids = IDUtils.genItemId();
			vip.setId(ids);
			vip.setUid(tbuser.getId());
			vip.setUname(tbuser.getNickname());
			DateTime  dataTime = new DateTime(new Date());
			dataTime = dataTime.plusDays(vip.getStatusdate());
			vip.setActivetimeend(dataTime.toDate());
			vip.setActivetimestart(new Date());
			vip.setCreated(new Date());
			vip.setUpdated(new Date());
			vipMapper.insert(vip);
		}
		VipExample viexample2 = new VipExample();
		VipExample.Criteria vipcriteria2 = viexample2.createCriteria();
		vipcriteria2.andUidEqualTo(vip.getUid());
		vipcriteria2.andActivetimestartLessThanOrEqualTo(new Date());
		vipcriteria2.andActivetimeendGreaterThanOrEqualTo(new Date());
		List<Vip> viplist2 = vipMapper.selectByExample(viexample2);
		return viplist2;
	}
	/**
	 * 生产用户的VIp优惠券信息
	 * 
	 * @param vip
	 * @return
	 */
	@Override
	public List<Vip> setNewVipInfo(Vip vip) {
		Double amounts[]={5.0,10.0,20.0};
		Double fullMoneys[]={50.0,100.0,200.0};
		// 查询改用户名下，有效期内可以使用的券
		TbUser tbuser = tbUserMapper.selectByPrimaryKey(vip.getUid());
		tbuser.setNewuser(1);
		tbUserMapper.updateByPrimaryKey(tbuser);
		for (int i = 0; i < 3; i++) {
			long ids = IDUtils.genItemId();
			vip.setId(ids);
			vip.setUid(tbuser.getId());
			vip.setUname(tbuser.getNickname());
			DateTime  dataTime = new DateTime(new Date());
			dataTime = dataTime.plusDays(vip.getStatusdate());
			vip.setActivetimeend(dataTime.toDate());
			vip.setActivetimestart(new Date());
			vip.setCreated(new Date());
			vip.setAmount(amounts[i]);
			vip.setFullMoney(fullMoneys[i]);
			vip.setUpdated(new Date());
			vipMapper.insert(vip);
		}
			
		VipExample viexample2 = new VipExample();
		VipExample.Criteria vipcriteria2 = viexample2.createCriteria();
		vipcriteria2.andUidEqualTo(vip.getUid());
		vipcriteria2.andActivetimestartLessThanOrEqualTo(new Date());
		vipcriteria2.andActivetimeendGreaterThanOrEqualTo(new Date());
		List<Vip> viplist2 = vipMapper.selectByExample(viexample2);
		return viplist2;
	}
	/**
	 * 获取用户的VIp优惠券信息
	 * 
	 * @param vip
	 * @return
	 */
	@Override
	public List<Vip> getVipInfo(Vip vip) {
		// 查询改用户名下，有效期内可以使用的券
		VipExample viexample2 = new VipExample();
		VipExample.Criteria vipcriteria2 = viexample2.createCriteria();
		vipcriteria2.andUidEqualTo(vip.getUid());
		vipcriteria2.andActivetimestartLessThanOrEqualTo(new Date());
		vipcriteria2.andActivetimeendGreaterThanOrEqualTo(new Date());
		List<Vip> viplist2 = vipMapper.selectByExample(viexample2);
		return viplist2;
	}
}
